<?php
/**
 * PostController is an instance of Controller (application.components). 
 *
 * Controller is an instance of CController (system.web).
 * CController manages a set of actions which deal with the corresponding user requests. 
 * Through the actions, CController coordinates the data flow between models and views. 
 *
 * Eduow :  International system for education (http://eduow.com)
 * Copyright 2010, Nikolay Stoitsev 
 *
 * Licensed under GNU General Public License version 2
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright     Copyright 2010
 * @link          http://eduow.com Eduow Project
 * @package       eduow
 * @subpackage    application.controllers
 * @inheritance   class PostController » Controller » CController » CBaseController » CComponent
 * @implements    
 * @since         Eduow v 0.0.1
 * @license       http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License version 2
 */

class PostController extends Controller
{
	/**
	 * @var string the default layout for the views. 
	 */
	public $layout='main';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			'view, index, newComment, print'=> array(Group::GUEST, 'min'),
			'create, favorite' => array(Group::USER, 'min'),
			'update, delete, admin' => array(Group::ADMIN, 'min'),
		);
	}

	/**
	 * Displays a particular model.
	 */
	public function actionView()
	{
		$post=$this->loadModel();
		$comment=$this->newComment($post);

		$this->render('view',array(
			'model'=>$post,
			'comment'=>$comment,
		));
	}

	/**
	 * Displays a particular model.
	 */
	public function actionProgram()
	{
		$this->render('program',array('model'=>$this->loadModel()));
	}

	/**
	 * Displays a particular model suitable for printing.
	 */
	public function actionPrint()
	{
		$post=$this->loadModel();

		$this->renderPartial('print',array(
			'data'=>$post
		));
	}

	/**
	 * Lists own models.
	 */
	public function actionMine()
	{
		$dataProvider=new CActiveDataProvider('Post',array(
		'criteria'=>array(
        		'condition'=>'author_id = '.Yii::app()->user->id,
			),
    		'pagination'=>array(
       			'pageSize'=>40,
    			),
		));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,	
			'message'=>Yii::t('yii','Your').' '
		));
	}


	/**
	 * Lists favorite posts.
	 */
	public function actionFavorite()
	{

		$criteria = 'user='.Yii::app()->user->id;
                $userfavs=Userdata::model()->find($criteria);		
		if(empty($userfavs->favorite)){
			$q = '0';
		}else{
			$q = implode(" OR id = ", json_decode($userfavs->favorite));
		}
		$dataProvider=new CActiveDataProvider('Post',array(
		'criteria'=>array(
        		'condition'=>'id = '.$q,
			),
    		'pagination'=>array(
       			'pageSize'=>40,
    			),
		));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,	
			'message'=>Yii::t('yii','Favorite').' '
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Post;
		if(isset($_POST['Post']))
		{
			$model->attributes=$_POST['Post'];
			if(!Yii::app()->user->hasAuth(Group::TEACHER)){
				$model->status=1;
			}
			if($model->save()){
				
				Yii::app()->user->setFlash('model',Yii::t('yii','Your post have been published succesfully. Thank you!'));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadModel();
		if(isset($_POST['Post']))
		{
			$model->attributes=$_POST['Post'];
			if($model->save())
				Yii::app()->user->setFlash('model',Yii::t('yii','Your post have been updated succesfully. Thank you!'));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will display a message.
	 */
	public function actionDelete()
	{
			
		$this->loadModel()->delete();

		$this->render('remove');
		
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria=new CDbCriteria(array(
			'condition'=>'status='.Post::STATUS_PUBLISHED,
			'order'=>'id DESC',
        		'limit'=>10,
			'with'=>'commentCount',
		));
		if(isset($_GET['tag']))
			$criteria->addSearchCondition('tags',$_GET['tag']);

		$dataProvider=new CActiveDataProvider('Post', array(
			'pagination'=>array(
				'pageSize'=>Yii::app()->params['postsPerPage'],
			),
			'criteria'=>$criteria,
		));

		$this->render('index',array(
			'dataProvider'=>$dataProvider,'message'=>Yii::t('yii','Last').' ',
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$dataProvider=new CActiveDataProvider('Post', array(
			'sort'=>array(
				'defaultOrder'=>'status, update_time DESC',
			),
		));

		$this->render('admin',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Suggests tags based on the current user input.
	 * This is called via AJAX when the user is entering the tags input.
	 */
	public function actionSuggestTags()
	{
		if(isset($_GET['q']) && ($keyword=trim($_GET['q']))!=='')
		{
			$tags=Tag::model()->suggestTags($keyword);
			if($tags!==array())
				echo implode("\n",$tags);
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
			{
				if(Yii::app()->user->isGuest)
					$condition='status='.Post::STATUS_PUBLISHED.' OR status='.POST::STATUS_ARCHIVED;
				else
					$condition='';
				$this->_model=Post::model()->findbyPk($_GET['id'], $condition);
			}
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}

	/**
	 * Creates a new comment.
	 * This method attempts to create a new comment based on the user input.
	 * If the comment is successfully created, the browser will be redirected
	 * to show the created comment.
	 * @param Post the post that the new comment belongs to
	 * @return Comment the comment instance
	 */
	protected function newComment($post)
	{
		$comment=new Comment;
		if(isset($_POST['Comment']))
		{
			$comment->attributes=$_POST['Comment'];
			$comment->status='1';
			if(!Yii::app()->user->isGuest){
				$comment->author=Yii::app()->user->model->username;
				$comment->email=Yii::app()->user->model->email;
				$comment->url=Yii::app()->user->model->website;
			}
			if($post->addComment($comment))
			{
				Yii::app()->user->setFlash('commentSubmitted',Yii::t('yii','Thank you for your comment.'));
			}
		}
		return $comment;
	}
}
